from flask import Blueprint, request, current_app
from werkzeug.utils import secure_filename
import json
import os
from utils import allowed_file, unique_filename
from modules.ocr.service import process_ocr

# 创建蓝图
ocr_blueprint = Blueprint('ocr', __name__)


@ocr_blueprint.route("/ocr", methods=["POST"])
def ocr_route():
    if "file" not in request.files:
        return {"error": "No file part"}, 400

    file = request.files["file"]
    if file.filename == "":
        return {"error": "No selected file"}, 400

    if file and allowed_file(file.filename, current_app.config["ALLOWED_EXTENSIONS"]):
        filename = unique_filename(secure_filename(file.filename))
        file_path = os.path.join(current_app.config["UPLOAD_FOLDER"], filename)
        file.save(file_path)
        file.close()  # Close the file

        try:
            param_lang = json.loads(request.form.get("data"))["lang"]
            lang = param_lang if param_lang else "en"
        except (KeyError, TypeError) as e:
            lang = "en"

        try:
            result = process_ocr(file_path, lang)
            os.remove(file_path)
            return {"message": result}, 200
        except AssertionError as e:
            os.remove(file_path)
            return {"error": repr(e)}, 400
    else:
        return {"error": "File not allowed"}, 400
